package com.example.androidstudy.ui.demo.paging3

import android.content.Context
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.paging.PagingSource
import androidx.room.*
import com.example.androidstudy.ui.demo.recyclerview.NumberInfo
import com.example.androidstudy.ui.demo.recyclerview.RecyclerViewAdapterDemo
import com.example.androidstudy.ui.demo.recyclerview.VHDemo

class Paging3AdapterData : PagingDataAdapter<NumberInfo, VHDemo>(RecyclerViewAdapterDemo.diff) {
    override fun onBindViewHolder(holder: VHDemo, position: Int) {
        getItem(position)?.let { holder.onBind(it) }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VHDemo {
        return VHDemo(parent)
    }

}

@Database(entities = [NumberInfo::class], version = 1, exportSchema = true)
abstract class NumberInfoDb : RoomDatabase() {
    companion object {
        fun create(context: Context, useInMemory: Boolean): NumberInfoDb {
            val databaseBuilder = if (useInMemory) {
                Room.inMemoryDatabaseBuilder(context, NumberInfoDb::class.java)
            } else {
                Room.databaseBuilder(context, NumberInfoDb::class.java, "NumberInfoDb.db")
            }
            return databaseBuilder
//                .fallbackToDestructiveMigration()
                .build()
        }
    }

    abstract fun dao(): NumberInfoDao
}

@Dao
interface NumberInfoDao {
    @Query("select * from NumberInfo order  by i  ASC")
    fun all(): PagingSource<Int, NumberInfo>

    @Query("delete from NumberInfo")
    suspend fun deleteAll()

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(data: List<NumberInfo>)

    @Query("select count(*) from NumberInfo")
    fun count(): Int
}